<template>
  <el-dialog :model-value="visible" title="订单详情" width="75%" @close="handleClose">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="120px"
      label-position="top"
    >
      <el-row :gutter="24">
        <!-- 第一列: 客户与收货信息 -->
        <el-col :span="8">
          <el-form-item label="客户信息" prop="customerName">
            <el-select
              v-model="formData.customerCode"
              placeholder="请选择企业客户"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="item in contractList"
                :key="item.id"
                :label="item.enterpriseName"
                :value="item.enterpriseCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户负责人" prop="accountManagerName">
            <el-select
              v-model="formData.accountManagerId"
              placeholder="请选择客户经理"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="manager in salesManagers"
                :key="manager.id"
                :label="manager.nickname"
                :value="manager.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="收货人" prop="consigneeName">
            <el-input v-model="formData.consigneeName" placeholder="请输入收货人姓名" disabled/>
          </el-form-item>
          <el-form-item label="联系号码" prop="contactPhoneNumber">
            <el-input v-model="formData.contactPhoneNumber" placeholder="请输入手机号码" disabled>
              <template #prepend>
                <el-select v-model="formData.contactPhoneCountryCode" style="width: 130px" disabled>
                  <!-- <el-option label="美国/加拿大 +1" value="+1" /> -->
                  <el-option label="中国 +86" value="+86" />
                  <!-- 可添加更多国家区号 -->
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="收货地址" required>
            <el-row :gutter="10" style="width: 100%">
              <el-col :span="24" style="margin-bottom: 10px">
                <el-form-item prop="shippingCity" style="margin-bottom: 0">
                  <el-select v-model="formData.shippingCity" placeholder="城市" style="width: 100%" disabled>
                    <el-option label="浙江省杭州市" value="330100" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="shippingState" style="margin-bottom: 0">
                  <el-select v-model="formData.shippingState" placeholder="州" style="width: 100%" disabled>
                    <el-option label="上城区" value="330102" />
                    <el-option label="拱墅区" value="330105" />
                    <el-option label="西湖区" value="330106" />
                    <el-option label="滨江区" value="330108" />
                    <el-option label="萧山区" value="330109" />
                    <el-option label="余杭区" value="330110" />
                    <el-option label="临平区" value="330113" />
                    <el-option label="钱塘区" value="330114" />
                    <el-option label="富阳区" value="330111" />
                    <el-option label="临安区" value="330112" />
                    <el-option label="建德市" value="330182" />
                    <el-option label="桐庐县" value="330122" />
                    <el-option label="淳安县" value="330127" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="shippingPostalCode" style="margin-bottom: 0">
                  <el-input v-model="formData.shippingPostalCode" placeholder="邮政编码" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24" style="margin-top: 10px">
                <el-form-item prop="shippingStreetAddress" style="margin-bottom: 0">
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="formData.shippingStreetAddress"
                    placeholder="请输入详细地址信息, 如道路、门牌号、小区、楼栋号、单元号等信息" disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

        <!-- 第二列: 日期与金额信息 -->
        <el-col :span="8">
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker
              v-model="formData.deliveryDate"
              type="date"
              placeholder="请选择交货日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              disabled
            />
          </el-form-item>
          <el-form-item label="交货预警 (天)" prop="deliveryWarningDays">
            <el-input-number
              v-model="formData.deliveryWarningDays"
              :min="0"
              placeholder="请输入交货预警天数"
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="收款日期" prop="paymentDueDate">
            <el-date-picker
              v-model="formData.paymentDueDate"
              type="date"
              placeholder="请选择收款日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              disabled
            />
          </el-form-item>
          <el-form-item label="收款预警 (天)" prop="paymentWarningDays">
            <el-input-number
              v-model="formData.paymentWarningDays"
              :min="0"
              placeholder="请输入收款预警天数"
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="合同单号" prop="contractNumber">
            <el-input v-model="formData.contractNumber" placeholder="请选择合同单号" disabled />
          </el-form-item>
          <el-form-item label="外部单号" prop="externalOrderNumber">
            <el-input
              v-model="formData.externalOrderNumber"
              placeholder="请输入外部单号"
              disabled
            />
          </el-form-item>
        </el-col>

        <!-- 第三列: 优惠与备注 -->
        <el-col :span="8">
          <el-form-item label="优惠比例 %" prop="discountPercentage">
            <el-input-number
              v-model="formData.discountPercentage"
              :precision="2"
              :min="0"
              :max="100"
              placeholder="0"
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="优惠金额" prop="discountAmount">
            <el-input-number
              v-model="formData.discountAmount"
              :precision="2"
              :min="0"
              placeholder="0.00"
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="优惠后金额" prop="amountAfterDiscount">
            <el-input-number
              v-model="formData.amountAfterDiscount"
              :precision="2"
              :min="0"
              placeholder="0.00"
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              :rows="12"
              placeholder="备注信息"
              maxlength="140"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 附件上传 -->
      <el-row>
        <el-col :span="24">
         <el-form-item label="附件">
        <!-- 使用我们新建的上传组件 -->
        <CustomUpload v-model="formData.files" :limit="10" :readOnly="true" />
      </el-form-item>
        </el-col>
      </el-row>
      <!-- 新增：BOM 信息表格 -->
      <el-row :gutter="24" style="margin-top: 20px;">
        <el-col :span="24">
          <BomInfoTable v-model="formData.orderItems" :readOnly="true" />
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { OrderVO } from '@/api/order'
import { ContractInfoApi } from '@/api/customer/contractinfo'
import { getSalesManager, UserVO } from '@/api/system/user'
import BomInfoTable from '@/components/BomInfoTable.vue'
import CustomUpload from './components/CustomUpload.vue'; 

// 定义Props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  initialData: {
    type: Object as () => OrderVO | null,
    default: null
  }
})

// 定义Emits
const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref<FormInstance>()

const contractList = ref([])
const salesManagers = ref<UserVO[]>([])

// 初始化表单数据
const getDefaultFormData = (): OrderVO => ({
  id: null,
  customerName: '',
  accountManagerName: '',
  consigneeName: '',
  contactPhoneCountryCode: '+86',
  contactPhoneNumber: '',
  shippingCity: '',
  shippingState: '',
  shippingPostalCode: '',
  shippingStreetAddress: '',
  deliveryDate: null,
  deliveryWarningDays: null,
  paymentDueDate: null,
  paymentWarningDays: null,
  contractNumber: '',
  externalOrderNumber: '',
  discountPercentage: null,
  discountAmount: null,
  amountAfterDiscount: null,
  remarks: '',
  orderItems: [],
  customerCode: null,
  accountManagerId: null,
  files: []
})

const formData = ref<OrderVO>(getDefaultFormData())

// 监听外部数据变化，用于编辑场景
watch(
  () => props.initialData,
  (newData) => {
    if (newData) {
      formData.value = { ...getDefaultFormData(), ...newData }
    } else {
      formData.value = getDefaultFormData()
    }
    formData.value.files = formData.value.files || []
  },
  { immediate: true, deep: true }
)

onMounted(async () => {
  try {
    const res = await ContractInfoApi.getContractInfoList()
    contractList.value = res || [] // 假设接口返回数据在data字段中
  } catch (error) {
    console.error('获取客户列表失败:', error)
  }
  try {
    const res = await getSalesManager() // 调用接口获取数据
    salesManagers.value = res || [] // 假设接口直接返回 UserVO 数组（根据实际接口返回调整）
  } catch (error) {
    console.error('获取销售经理列表失败:', error)
  }
})

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  formData.value = getDefaultFormData()
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

/* 自定义上传文件列表项样式 */
.custom-file-item {
  display: flex;
  width: 280px; /* 根据需要调整宽度 */
  padding: 8px;
  margin-right: 8px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  align-items: center;
  justify-content: space-between;
}

.file-icon {
  margin-right: 8px;
  font-size: 24px;
  color: #606266;
}

.file-name {
  overflow: hidden;
  font-size: 14px;
  color: #303133;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-grow: 1;
}

.file-size {
  margin-right: 8px;
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.delete-icon {
  color: #909399;
  cursor: pointer;
}

.delete-icon:hover {
  color: #f56c6c;
}

/* 覆盖el-upload的默认列表样式 */
:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: auto;

  display: flex;
  flex-wrap: wrap;
}

:deep(.el-upload-list__item) {
  width: auto;
  height: auto;
  background-color: transparent;
  border: none;
}

:deep(.el-upload--picture-card) {
  display: none; /* 隐藏加号上传框，只用按钮上传 */
}

/* 调整el-form-item的label样式以匹配原型 */
:deep(.el-form-item__label) {
  margin-bottom: 6px !important;
  font-weight: 500;
  line-height: 22px;
  color: #606266;
}

/* 必填项的星号 */
:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before) {
  margin-right: 4px;
  color: var(--el-color-danger);
  content: '*';
}
</style>
